import { useEffect, useRef, useState } from 'react';
import Modal, {BaseModalProps} from '../Modal'
import Button from "components/Button";
import classnames from 'classnames'
import './index.scss'

type MousePosition = { x: number, y: number } | null

let mousePosition: MousePosition

const getClickPosition = (e: MouseEvent) => {
  mousePosition = {
    x: e.pageX,
    y: e.pageY
  }
  setTimeout(() => {
    mousePosition = null
  }, 100)
}
 
document.documentElement.addEventListener('click', getClickPosition, true)

function setTransformOrigin(node: HTMLDivElement, value: string) {
  var style = node.style;
  ['Webkit', 'Moz', 'Ms', 'ms'].forEach(function (prefix) {
    // @ts-ignore
    style[prefix + 'TransformOrigin'] = value;
  });
  style['transformOrigin'] = value;
}

function offset(el: HTMLDivElement) {
  const rect = el.getBoundingClientRect()
  const pos = {
    left: rect.left,
    top: rect.top
  }
  const doc = el.ownerDocument
  const w = doc.defaultView
  pos.left += getScroll(w)
  pos.top += getScroll(w, 1)
  return pos
}

// 1st use window.pageXOffset and window.pageYOffset
// 2nd use window.document.documentElement.scrollLeft/scrollTop
// 3rd use window.document.body.scrollLeft/scrollTop
function getScroll(w: any, top?: number) {
  var ret = w['page' + (top ? 'Y' : 'X') + 'Offset'];
  var method = 'scroll' + (top ? 'Top' : 'Left');
  if (typeof ret !== 'number') {
    var d = w.document;
    ret = d.documentElement[method];
    if (typeof ret !== 'number') {
      ret = d.body[method];
    }
  }
  return ret;
}

export interface BaseDialogProps extends BaseModalProps {
  title?: string,
  children?: React.ReactNode,
  onSure?: () => any,
  onCancel?: () => any
}

export default function Dialog(props: BaseDialogProps) {
  const {title, show, onClose, children, onSure, onCancel} = props
  const [display, setDisplay] = useState(false)
  const wrapperRef = useRef<HTMLDivElement>(null)

  function clickHander(e: React.MouseEvent<Element, MouseEvent>) {
    e.stopPropagation()
  }

  function sureClickHander(e: React.MouseEvent<Element, MouseEvent>) {
    e.stopPropagation()
    onSure && onSure()
  }

  function animationendHandler() {
    if (!show) {
      setDisplay(false)
    }
  }

  const cls = classnames('dialog-wrapper', {
    in: show,
    out: !show
  })

  useEffect(() => {
    if (show) {
      document.body.style.overflow = 'hidden'
      setDisplay(true)
    } else {
      document.body.style.overflow = 'visible'
    }
  }, [show])

  useEffect(() => {
    const node = wrapperRef.current
    if (display && node) {
      const elOffset = offset(node)

      if (mousePosition)
      setTransformOrigin(node, mousePosition.x - elOffset.left + 'px ' + (mousePosition.y - elOffset.top) + 'px')
    }
  }, [display])
  
  return (
    <Modal show={show} onClose={onClose}>
      {display ? (
        <div ref={wrapperRef} className={cls} onClick={clickHander} onAnimationEnd={animationendHandler}>
          <div className="header">
            <div className="title">{title}</div>
            <div className="close" onClick={onClose}>x</div>
          </div>
          <div className="content">{children}</div>
          <div className="footer">
            <Button type="primary" size="small" onClick={sureClickHander}>确认</Button>
          </div>
        </div>
      ) : null}
    </Modal>
  )
}
